from functools import wraps
from flask import session, jsonify, request, redirect, url_for

from applications.models import User

# login_required装饰器 验证session
def login_required(fn):
    @wraps(fn)
    def inner(*args, **kwargs):
        # 确保在请求上下文中
        if 'user_id' in session:
            user_id = session.get('user_id')
            user = User.query.get(user_id)
            if user:
                request.user = user
                return fn(*args, **kwargs)
            else:
                # 用户不存在的处理逻辑
                print('request.url', request.url)
                return redirect(url_for('login.login', next=request.url))
        else:
            # 用户未登录的处理逻辑
            return redirect(url_for('login.login', next=request.url))
    return inner